package cn.iocoder.yudao.module.signature.validatap12status.util;

import cn.hutool.core.codec.Base64Decoder;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.iocoder.yudao.module.signature.validatap12status.dto.*;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import java.io.ByteArrayInputStream;
import java.security.KeyStore;
import java.security.Security;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author liujq
 * @date 20241026 21:53
 */
@Slf4j
public class CertUtil {

    public static void getCertInfo(String certStr, String passwd, CertStatusDTO certStatusDTO) throws Exception {
        byte[] p12Byte = Base64Decoder.decode(certStr);
        // 添加BouncyCastle支持
        Security.addProvider(new BouncyCastleProvider());
        // 加载证书
        KeyStore keyStore = KeyStore.getInstance("PKCS12", "BC");
        keyStore.load(new ByteArrayInputStream(p12Byte), passwd.toCharArray());
        Enumeration<String> aliases = keyStore.aliases();
        String alias = "1";
        while (aliases.hasMoreElements()) {
            alias = aliases.nextElement();
        }
        Certificate certificate = keyStore.getCertificate(alias);
        if (certificate != null) {
            if (certificate instanceof X509Certificate) {
                X509Certificate x509Certificate = (X509Certificate) certificate;
                Date notBefore = x509Certificate.getNotBefore();
                certStatusDTO.setCertCreateTime(DateUtil.format(notBefore, "yyyy-MM-dd HH:mm:ss"));
                Date notAfter = x509Certificate.getNotAfter();
                certStatusDTO.setCertExpireTime(DateUtil.format(notAfter, "yyyy-MM-dd HH:mm:ss"));
                certStatusDTO.setCertSerialNumber(x509Certificate.getSerialNumber().toString());
                certStatusDTO.setCertRemainingDays(DateUtil.between(new Date(), notAfter,DateUnit.DAY ,false));
            } else {
                log.error("Invalid certificate type. Not an X.509 certificate.");
                throw new Exception("Invalid certificate type. Not an X.509 certificate.");
            }
        } else {
            log.error("Certificate not found for the given alias.");
            throw new Exception("Certificate not found for the given alias.");
        }

    }

    public static String getCertName(String getSubjectDNStr) {
        log.info("getSubjectDNStr:{}", getSubjectDNStr);
        String patternString = "O=([^,]*)";
        Pattern pattern = Pattern.compile(patternString);
        Matcher matcher = pattern.matcher(getSubjectDNStr);
        return matcher.find() ? matcher.group(1).replaceAll("\"", "") : null;
    }

    public static String getTeamId(String getSubjectDNStr) {
        String patternString = "OU=([^,]*)";
        Pattern pattern = Pattern.compile(patternString);
        Matcher matcher = pattern.matcher(getSubjectDNStr);
        return matcher.find() ? matcher.group(1).replaceAll("\"", "") : null;
    }

    /**
     * 验证证书和描述文件
     *
     * @param certStr       证书base64字符串
     * @param mobileContent 描述文件内容
     * @param password      证书密码
     * @return CertAndMobileprovisionDTO
     * @throws Exception 异常信息
     */
    public static CertAndMobileprovisionDTO checkMobileProvesion(String certStr, String mobileContent, String password) throws Exception {

        log.info("certStr:{},password:{}", certStr, password);

        CertInfoDTO certAllInfo = OCSPUtil.getCertAllInfo(certStr, password);
        log.info("certAllInfo:{}", JSON.toJSONString(certAllInfo));

        Map<String, String> mobileInfo = getMobileInfo(mobileContent);
        log.info("mobileInfo:{}", JSON.toJSONString(mobileInfo));


        List<DeviceInfoDTO> deviceInfoList = getDeviceInfoList(mobileContent);
        log.info("deviceInfoList:{}", JSON.toJSONString(deviceInfoList));

        List<CapabilityDTO> allCapabilities = getAllCapabilities(mobileContent);
        log.info("allCapabilities:{}", JSON.toJSONString(allCapabilities));

        String teamName = mobileInfo.get("teamName");
        String teamId = mobileInfo.get("teamId");
        String expirationDate = mobileInfo.get("expirationDate");
        String creationDate = mobileInfo.get("creationDate");
        String bundleId = mobileInfo.get("bundleId");
        String uuid=  mobileInfo.get("uuid");
        String profileName=  mobileInfo.get("profileName");



        CertAndMobileprovisionDTO certAndMobileprovisionDTO = new CertAndMobileprovisionDTO();
        DateTime expireDateParse = StringUtils.isBlank(expirationDate) ? null : DateUtil.parse(expirationDate, "yyyy-MM-dd'T'HH:mm:ss'Z'");
        DateTime createDateParse = StringUtils.isBlank(creationDate) ? null : DateUtil.parse(creationDate, "yyyy-MM-dd'T'HH:mm:ss'Z'");

        certAndMobileprovisionDTO.setCertInfoDTO(certAllInfo);
        certAndMobileprovisionDTO.setUuid(uuid);
        certAndMobileprovisionDTO.setBundleId(bundleId);
        certAndMobileprovisionDTO.setMobileprovisionCreateTime(createDateParse);
        certAndMobileprovisionDTO.setMobileprovisionExpireTime(expireDateParse);
        if(null!=expireDateParse){
            certAndMobileprovisionDTO.setMobileprovisionRemainingDays(DateUtil.between(new Date(),expireDateParse,DateUnit.DAY, false));
        }

        certAndMobileprovisionDTO.setMatchFlag(Objects.equals(certAllInfo.getTeamId(), teamId));
        certAndMobileprovisionDTO.setTeamId(teamId);
        certAndMobileprovisionDTO.setTeamName(teamName);

        certAndMobileprovisionDTO.setDeviceInfoList(deviceInfoList);
        certAndMobileprovisionDTO.setAllCapabilities(allCapabilities);
        certAndMobileprovisionDTO.setProfileName(profileName);

        return certAndMobileprovisionDTO;
    }

    /**
     * 从描述文件中提取信息
     *
     * @param inputString 描述文件内容
     * @return Map<String, String> 包含团队名称、团队ID、创建时间、过期时间等信息
     */
    private static Map<String, String> getMobileInfo(String inputString) {
        Map<String, String> res = new HashMap<>(16);
        String expirationDatePatternString = "<key>ExpirationDate</key>\\s*<date>(.*?)</date>";
        String creationDatePatternString = "<key>CreationDate</key>\\s*<date>(.*?)</date>";
        String namePatternString = "<key>TeamName</key>\\s*<string>(.*?)</string>";
        String teamIdPatternString = "<key>TeamIdentifier</key>\\s*<array>\\s*<string>(.*?)</string>\\s*</array>";
        String bundleIdPatternString = "<key>application-identifier</key>\\s*<string>(.*?)</string>";
        String uuidPatternString = "<key>UUID</key>\\s*<string>(.*?)</string>";
        String profileNamePatternString = "<key>Name</key>\\s*<string>(.*?)</string>";
        Pattern expirationDatePattern = Pattern.compile(expirationDatePatternString);
        Pattern creationDatePattern = Pattern.compile(creationDatePatternString);
        Pattern namePattern = Pattern.compile(namePatternString);
        Pattern teamIdPattern = Pattern.compile(teamIdPatternString);
        Pattern bundleIdPattern = Pattern.compile(bundleIdPatternString);
        Pattern uuidPattern = Pattern.compile(uuidPatternString);
        Pattern profileNamePattern = Pattern.compile(profileNamePatternString);

        Matcher expirationDateMatcher = expirationDatePattern.matcher(inputString);
        Matcher creationDateMatcher = creationDatePattern.matcher(inputString);
        Matcher nameMatcher = namePattern.matcher(inputString);
        Matcher teamIdMatcher = teamIdPattern.matcher(inputString);
        Matcher bundleIdMatcher = bundleIdPattern.matcher(inputString);
        Matcher uuidMatcher = uuidPattern.matcher(inputString);
        Matcher profileNameMatcher = profileNamePattern.matcher(inputString);
        if (expirationDateMatcher.find()) {
            res.put("expirationDate", expirationDateMatcher.group(1));
        }
        if (creationDateMatcher.find()) {
            res.put("creationDate", creationDateMatcher.group(1));
        }
        if (nameMatcher.find()) {
            res.put("teamName", nameMatcher.group(1).trim());
        }
        if (teamIdMatcher.find()) {
            res.put("teamId", teamIdMatcher.group(1).trim());
        }
        if (bundleIdMatcher.find()) {
            res.put("bundleId", bundleIdMatcher.group(1).trim());
        }
        if (uuidMatcher.find()) {
            res.put("uuid", uuidMatcher.group(1).trim());
        }
        if (profileNameMatcher.find()) {
            res.put("profileName", profileNameMatcher.group(1).trim());
        }
        return res;
    }

    /**
     * 获取描述文件中的所有设备信息
     *
     * @param inputString 描述文件内容
     * @return 设备信息列表
     */
    public static List<DeviceInfoDTO> getDeviceInfoList(String inputString) {
        List<DeviceInfoDTO> deviceInfoList = new ArrayList<>();
        
        // 提取设备UDID列表
        String deviceUdidPatternString = "<key>ProvisionedDevices</key>\\s*<array>(.*?)</array>";
        Pattern deviceUdidPattern = Pattern.compile(deviceUdidPatternString, Pattern.DOTALL);
        Matcher deviceUdidMatcher = deviceUdidPattern.matcher(inputString);
        
        if (deviceUdidMatcher.find()) {
            String devicesContent = deviceUdidMatcher.group(1);
            Pattern udidPattern = Pattern.compile("<string>(.*?)</string>");
            Matcher udidMatcher = udidPattern.matcher(devicesContent);
            
            while (udidMatcher.find()) {
                String udid = udidMatcher.group(1).trim();
                DeviceInfoDTO deviceInfo = new DeviceInfoDTO();
                deviceInfo.setUdid(udid);
                
                // 提取设备详细信息
                String deviceInfoPatternString = "<key>" + udid + "</key>\\s*<dict>(.*?)</dict>";
                Pattern deviceInfoPattern = Pattern.compile(deviceInfoPatternString, Pattern.DOTALL);
                Matcher deviceInfoMatcher = deviceInfoPattern.matcher(inputString);
                
                if (deviceInfoMatcher.find()) {
                    String deviceDetail = deviceInfoMatcher.group(1);
                    
                    // 提取设备UUID
                    Pattern uuidPattern = Pattern.compile("<key>UUID</key>\\s*<string>(.*?)</string>");
                    Matcher uuidMatcher = uuidPattern.matcher(deviceDetail);
                    if (uuidMatcher.find()) {
                        deviceInfo.setUuid(uuidMatcher.group(1).trim());
                    }
                    
                    // 提取设备名称
                    Pattern namePattern = Pattern.compile("<key>name</key>\\s*<string>(.*?)</string>");
                    Matcher nameMatcher = namePattern.matcher(deviceDetail);
                    if (nameMatcher.find()) {
                        deviceInfo.setName(nameMatcher.group(1).trim());
                    }
                    
                    // 提取设备类型
                    Pattern classPattern = Pattern.compile("<key>deviceClass</key>\\s*<string>(.*?)</string>");
                    Matcher classMatcher = classPattern.matcher(deviceDetail);
                    if (classMatcher.find()) {
                        deviceInfo.setDeviceClass(classMatcher.group(1).trim());
                    }
                    
                    // 提取设备型号
                    Pattern modelPattern = Pattern.compile("<key>model</key>\\s*<string>(.*?)</string>");
                    Matcher modelMatcher = modelPattern.matcher(deviceDetail);
                    if (modelMatcher.find()) {
                        deviceInfo.setModel(modelMatcher.group(1).trim());
                    }
                    
                    // 提取设备平台
                    Pattern platformPattern = Pattern.compile("<key>platform</key>\\s*<string>(.*?)</string>");
                    Matcher platformMatcher = platformPattern.matcher(deviceDetail);
                    if (platformMatcher.find()) {
                        deviceInfo.setPlatform(platformMatcher.group(1).trim());
                    }
                    
                    // 提取设备状态
                    Pattern statusPattern = Pattern.compile("<key>status</key>\\s*<string>(.*?)</string>");
                    Matcher statusMatcher = statusPattern.matcher(deviceDetail);
                    if (statusMatcher.find()) {
                        deviceInfo.setStatus(statusMatcher.group(1).trim());
                    }
                }
                
                deviceInfoList.add(deviceInfo);
            }
        }
        
        return deviceInfoList;
    }

    /**
     * 获取描述文件中的能力信息
     *
     * @param inputString 描述文件内容
     * @return 能力信息
     */
    public static EntitlementsDTO getEntitlements(String inputString) {
        EntitlementsDTO entitlements = new EntitlementsDTO();
        entitlements.setOtherCapabilities(new HashMap<>());
        
        // 提取Entitlements部分
        String entitlementsPatternString = "<key>Entitlements</key>\\s*<dict>(.*?)</dict>";
        Pattern entitlementsPattern = Pattern.compile(entitlementsPatternString, Pattern.DOTALL);
        Matcher entitlementsMatcher = entitlementsPattern.matcher(inputString);
        
        if (entitlementsMatcher.find()) {
            String entitlementsContent = entitlementsMatcher.group(1);
            
            // 提取应用组标识符
            Pattern appIdPattern = Pattern.compile("<key>application-identifier</key>\\s*<string>(.*?)</string>");
            Matcher appIdMatcher = appIdPattern.matcher(entitlementsContent);
            if (appIdMatcher.find()) {
                entitlements.setApplicationIdentifier(appIdMatcher.group(1).trim());
            }
            
            // 提取团队标识符
            Pattern teamIdPattern = Pattern.compile("<key>com.apple.developer.team-identifier</key>\\s*<string>(.*?)</string>");
            Matcher teamIdMatcher = teamIdPattern.matcher(entitlementsContent);
            if (teamIdMatcher.find()) {
                entitlements.setTeamIdentifier(teamIdMatcher.group(1).trim());
            }
            
            // 提取推送通知
            Pattern apsPattern = Pattern.compile("<key>aps-environment</key>\\s*<string>(.*?)</string>");
            Matcher apsMatcher = apsPattern.matcher(entitlementsContent);
            if (apsMatcher.find()) {
                entitlements.setApsEnvironment(true);
            }
            
            // 提取应用组
            Pattern appGroupsPattern = Pattern.compile("<key>com.apple.security.application-groups</key>\\s*<array>(.*?)</array>");
            Matcher appGroupsMatcher = appGroupsPattern.matcher(entitlementsContent);
            if (appGroupsMatcher.find()) {
                String appGroupsContent = appGroupsMatcher.group(1);
                List<String> appGroups = new ArrayList<>();
                Pattern groupPattern = Pattern.compile("<string>(.*?)</string>");
                Matcher groupMatcher = groupPattern.matcher(appGroupsContent);
                while (groupMatcher.find()) {
                    appGroups.add(groupMatcher.group(1).trim());
                }
                entitlements.setAppGroups(appGroups.toArray(new String[0]));
            }
            
            // 提取后台模式
            Pattern backgroundModesPattern = Pattern.compile("<key>UIBackgroundModes</key>\\s*<array>(.*?)</array>");
            Matcher backgroundModesMatcher = backgroundModesPattern.matcher(entitlementsContent);
            if (backgroundModesMatcher.find()) {
                String backgroundModesContent = backgroundModesMatcher.group(1);
                List<String> backgroundModes = new ArrayList<>();
                Pattern modePattern = Pattern.compile("<string>(.*?)</string>");
                Matcher modeMatcher = modePattern.matcher(backgroundModesContent);
                while (modeMatcher.find()) {
                    backgroundModes.add(modeMatcher.group(1).trim());
                }
                entitlements.setBackgroundModes(backgroundModes.toArray(new String[0]));
            }
            
            // 提取数据保护
            Pattern dataProtectionPattern = Pattern.compile("<key>com.apple.developer.default-data-protection</key>\\s*<string>(.*?)</string>");
            Matcher dataProtectionMatcher = dataProtectionPattern.matcher(entitlementsContent);
            if (dataProtectionMatcher.find()) {
                entitlements.setDataProtection(dataProtectionMatcher.group(1).trim());
            }
            
            // 提取健康包
            Pattern healthKitPattern = Pattern.compile("<key>com.apple.developer.healthkit</key>\\s*<true/>");
            Matcher healthKitMatcher = healthKitPattern.matcher(entitlementsContent);
            entitlements.setHealthKit(healthKitMatcher.find());
            
            // 提取健康包更新
            Pattern healthKitUpdatePattern = Pattern.compile("<key>com.apple.developer.healthkit.update</key>\\s*<true/>");
            Matcher healthKitUpdateMatcher = healthKitUpdatePattern.matcher(entitlementsContent);
            entitlements.setHealthKitUpdate(healthKitUpdateMatcher.find());
            
            // 提取家庭共享
            Pattern homeKitPattern = Pattern.compile("<key>com.apple.developer.homekit</key>\\s*<true/>");
            Matcher homeKitMatcher = homeKitPattern.matcher(entitlementsContent);
            entitlements.setHomeKit(homeKitMatcher.find());
            
            // 提取钥匙串访问组
            Pattern keychainPattern = Pattern.compile("<key>keychain-access-groups</key>\\s*<array>(.*?)</array>");
            Matcher keychainMatcher = keychainPattern.matcher(entitlementsContent);
            if (keychainMatcher.find()) {
                String keychainContent = keychainMatcher.group(1);
                List<String> keychainGroups = new ArrayList<>();
                Pattern groupPattern = Pattern.compile("<string>(.*?)</string>");
                Matcher groupMatcher = groupPattern.matcher(keychainContent);
                while (groupMatcher.find()) {
                    keychainGroups.add(groupMatcher.group(1).trim());
                }
                entitlements.setKeychainAccessGroups(keychainGroups.toArray(new String[0]));
            }
            
            // 提取个人VPN
            Pattern vpnPattern = Pattern.compile("<key>com.apple.developer.networking.personal-vpn</key>\\s*<true/>");
            Matcher vpnMatcher = vpnPattern.matcher(entitlementsContent);
            entitlements.setPersonalVPN(vpnMatcher.find());
            
            // 提取钱包
            Pattern walletPattern = Pattern.compile("<key>com.apple.developer.pass-type-identifiers</key>\\s*<array>(.*?)</array>");
            Matcher walletMatcher = walletPattern.matcher(entitlementsContent);
            if (walletMatcher.find()) {
                String walletContent = walletMatcher.group(1);
                List<String> walletIds = new ArrayList<>();
                Pattern idPattern = Pattern.compile("<string>(.*?)</string>");
                Matcher idMatcher = idPattern.matcher(walletContent);
                while (idMatcher.find()) {
                    walletIds.add(idMatcher.group(1).trim());
                }
                entitlements.setWallet(walletIds.toArray(new String[0]));
            }
            
            // 提取无线配件配置
            Pattern wirelessPattern = Pattern.compile("<key>com.apple.external-accessory.wireless-configuration</key>\\s*<true/>");
            Matcher wirelessMatcher = wirelessPattern.matcher(entitlementsContent);
            entitlements.setWirelessAccessoryConfiguration(wirelessMatcher.find());
            
            // 提取其他能力
            Pattern otherPattern = Pattern.compile("<key>([^<]+)</key>\\s*<([^>]+)>(.*?)</\\2>");
            Matcher otherMatcher = otherPattern.matcher(entitlementsContent);
            while (otherMatcher.find()) {
                String key = otherMatcher.group(1).trim();
                String type = otherMatcher.group(2).trim();
                String value = otherMatcher.group(3).trim();
                
                // 跳过已经处理过的能力
                if (!key.equals("application-identifier") && 
                    !key.equals("com.apple.developer.team-identifier") &&
                    !key.equals("aps-environment") &&
                    !key.equals("com.apple.security.application-groups") &&
                    !key.equals("UIBackgroundModes") &&
                    !key.equals("com.apple.developer.default-data-protection") &&
                    !key.equals("com.apple.developer.healthkit") &&
                    !key.equals("com.apple.developer.healthkit.update") &&
                    !key.equals("com.apple.developer.homekit") &&
                    !key.equals("keychain-access-groups") &&
                    !key.equals("com.apple.developer.networking.personal-vpn") &&
                    !key.equals("com.apple.developer.pass-type-identifiers") &&
                    !key.equals("com.apple.external-accessory.wireless-configuration")) {
                    
                    Object parsedValue = parseValue(type, value);
                    entitlements.getOtherCapabilities().put(key, parsedValue);
                }
            }
        }
        
        return entitlements;
    }
    
    /**
     * 解析值
     *
     * @param type 类型
     * @param value 值
     * @return 解析后的值
     */
    private static Object parseValue(String type, String value) {
        switch (type) {
            case "string":
                return value;
            case "true":
                return true;
            case "false":
                return false;
            case "array":
                List<String> arrayValues = new ArrayList<>();
                Pattern pattern = Pattern.compile("<string>(.*?)</string>");
                Matcher matcher = pattern.matcher(value);
                while (matcher.find()) {
                    arrayValues.add(matcher.group(1).trim());
                }
                return arrayValues;
            default:
                return value;
        }
    }

    /**
     * 获取描述文件中的所有能力信息
     *
     * @param inputString 描述文件内容
     * @return 能力信息列表
     */
    public static List<CapabilityDTO> getAllCapabilities(String inputString) {
        List<CapabilityDTO> capabilities = new ArrayList<>();
        
        // 提取Entitlements部分
        String entitlementsPatternString = "<key>Entitlements</key>\\s*<dict>(.*?)</dict>";
        Pattern entitlementsPattern = Pattern.compile(entitlementsPatternString, Pattern.DOTALL);
        Matcher entitlementsMatcher = entitlementsPattern.matcher(inputString);
        
        if (entitlementsMatcher.find()) {
            String entitlementsContent = entitlementsMatcher.group(1);
            
            // 定义能力映射
            Map<String, String> capabilityMap = new HashMap<>();
            capabilityMap.put("com.apple.developer.networking.wifi-info", "ACCESS_WIFI_INFORMATION");
            capabilityMap.put("com.apple.developer.applesignin", "APPLE_ID_AUTH");
            capabilityMap.put("com.apple.developer.in-app-payments", "APPLE_PAY");
            capabilityMap.put("com.apple.security.application-groups", "APP_GROUPS");
            capabilityMap.put("com.apple.developer.associated-domains", "ASSOCIATED_DOMAINS");
            capabilityMap.put("com.apple.developer.authentication-services.autofill-credentials", "AUTOFILL_CREDENTIAL_PROVIDER");
            capabilityMap.put("com.apple.developer.icloud-container-identifiers", "CLASSKIT");
            capabilityMap.put("com.apple.developer.coremedia.hls-low-latency", "COREMEDIA_HLS_LOW_LATENCY");
            capabilityMap.put("com.apple.developer.default-data-protection", "DATA_PROTECTION");
            capabilityMap.put("com.apple.developer.game-center", "GAME_CENTER");
            capabilityMap.put("com.apple.developer.healthkit", "HEALTHKIT");
            capabilityMap.put("com.apple.developer.homekit", "HOMEKIT");
            capabilityMap.put("com.apple.developer.networking.HotspotConfiguration", "HOT_SPOT");
            capabilityMap.put("com.apple.developer.icloud-container-identifiers", "ICLOUD");
            capabilityMap.put("com.apple.developer.inter-app-audio", "INTER_APP_AUDIO");
            capabilityMap.put("com.apple.developer.in-app-payments", "IN_APP_PURCHASE");
            capabilityMap.put("com.apple.developer.maps", "MAPS");
            capabilityMap.put("com.apple.developer.networking.multipath", "MULTIPATH");
            capabilityMap.put("com.apple.developer.networking.custom-protocol", "NETWORK_CUSTOM_PROTOCOL");
            capabilityMap.put("com.apple.developer.networking.networkextension", "NETWORK_EXTENSIONS");
            capabilityMap.put("com.apple.developer.nfc.readersession.formats", "NFC_TAG_READING");
            capabilityMap.put("com.apple.developer.networking.personal-vpn", "PERSONAL_VPN");
            capabilityMap.put("aps-environment", "PUSH_NOTIFICATIONS");
            capabilityMap.put("com.apple.developer.siri", "SIRIKIT");
            capabilityMap.put("com.apple.developer.system-extension.install", "SYSTEM_EXTENSION_INSTALL");
            capabilityMap.put("com.apple.developer.user-management", "USER_MANAGEMENT");
            capabilityMap.put("com.apple.developer.pass-type-identifiers", "WALLET");
            capabilityMap.put("com.apple.external-accessory.wireless-configuration", "WIRELESS_ACCESSORY_CONFIGURATION");
            capabilityMap.put("com.apple.developer.kernel.extended-virtual-addressing", "EXTENDED_VIRTUAL_ADDRESSING");
            capabilityMap.put("com.apple.developer.kernel.increased-memory-limit", "INCREASED_MEMORY_LIMIT");
            capabilityMap.put("com.apple.developer.kernel.increased-memory-limit-debugging", "INCREASED_MEMORY_LIMIT_DEBUGGING");
            capabilityMap.put("com.apple.developer.usernotifications.communication", "USERNOTIFICATIONS_COMMUNICATION");
            capabilityMap.put("com.apple.developer.usernotifications.time-sensitive", "USERNOTIFICATIONS_TIMESENSITIVE");
            capabilityMap.put("com.apple.developer.weatherkit", "WEATHERKIT");
            capabilityMap.put("com.apple.developer.healthkit.recalibrate-estimates", "HEALTHKIT_RECALIBRATE_ESTIMATES");
            capabilityMap.put("com.apple.developer.healthkit.access", "HEALTHKIT_ACCESS");
            capabilityMap.put("keychain-access-groups", "KEYCHAIN_ACCESS_GROUPS");
            capabilityMap.put("com.apple.developer.healthkit.background-delivery", "HEALTHKIT_BACKGROUND_DELIVERY");
            
            // 定义能力描述映射
            Map<String, String> descriptionMap = new HashMap<>();
            descriptionMap.put("ACCESS_WIFI_INFORMATION", "Wi-Fi 信息访问");
            descriptionMap.put("APPLE_ID_AUTH", "Apple ID 认证");
            descriptionMap.put("APPLE_PAY", "Apple Pay 支付");
            descriptionMap.put("APP_GROUPS", "应用组共享");
            descriptionMap.put("ASSOCIATED_DOMAINS", "关联域名");
            descriptionMap.put("AUTOFILL_CREDENTIAL_PROVIDER", "自动填充凭据");
            descriptionMap.put("CLASSKIT", "ClassKit 支持");
            descriptionMap.put("COREMEDIA_HLS_LOW_LATENCY", "低延迟 HLS 流媒体");
            descriptionMap.put("DATA_PROTECTION", "数据保护");
            descriptionMap.put("GAME_CENTER", "Game Center 支持");
            descriptionMap.put("HEALTHKIT", "健康数据");
            descriptionMap.put("HEALTHKIT_RECALIBRATE_ESTIMATES", "健康数据校准");
            descriptionMap.put("HOMEKIT", "家庭自动化");
            descriptionMap.put("HOT_SPOT", "个人热点");
            descriptionMap.put("ICLOUD", "iCloud 支持");
            descriptionMap.put("INTER_APP_AUDIO", "应用间音频");
            descriptionMap.put("IN_APP_PURCHASE", "应用内购买");
            descriptionMap.put("MAPS", "地图服务");
            descriptionMap.put("MULTIPATH", "多路径传输");
            descriptionMap.put("NETWORK_CUSTOM_PROTOCOL", "自定义网络协议");
            descriptionMap.put("NETWORK_EXTENSIONS", "网络扩展功能");
            descriptionMap.put("NFC_TAG_READING", "NFC 标签读取");
            descriptionMap.put("PERSONAL_VPN", "个人 VPN");
            descriptionMap.put("PUSH_NOTIFICATIONS", "推送通知");
            descriptionMap.put("SIRIKIT", "Siri 支持");
            descriptionMap.put("SYSTEM_EXTENSION_INSTALL", "系统扩展安装");
            descriptionMap.put("USER_MANAGEMENT", "用户管理");
            descriptionMap.put("WALLET", "Wallet 支持");
            descriptionMap.put("WIRELESS_ACCESSORY_CONFIGURATION", "无线配件配置");
            descriptionMap.put("EXTENDED_VIRTUAL_ADDRESSING", "扩展虚拟地址支持");
            descriptionMap.put("INCREASED_MEMORY_LIMIT", "拓展内存限制");
            descriptionMap.put("INCREASED_MEMORY_LIMIT_DEBUGGING", "拓展内存限制调试");
            descriptionMap.put("USERNOTIFICATIONS_COMMUNICATION", "基础通知权限");
            descriptionMap.put("USERNOTIFICATIONS_TIMESENSITIVE", "实时通知权限");
            descriptionMap.put("WEATHERKIT", "天气服务");
            descriptionMap.put("HEALTHKIT_ACCESS", "健康数据访问权限");
            descriptionMap.put("KEYCHAIN_ACCESS_GROUPS", "钥匙串访问组");
            descriptionMap.put("HEALTHKIT_BACKGROUND_DELIVERY", "健康数据后台更新");
            
            // 检查每个能力是否启用
            for (Map.Entry<String, String> entry : capabilityMap.entrySet()) {
                String key = entry.getKey();
                String code = entry.getValue();
                String description = descriptionMap.get(code);
                
                CapabilityDTO capability = new CapabilityDTO();
                capability.setCode(code);
                capability.setDescription(description);
                
                // 检查能力是否启用
                boolean enabled = false;
                if (key.contains(".")) {
                    // 对于复杂的能力，检查是否存在对应的key
                    Pattern pattern = Pattern.compile("<key>" + key + "</key>\\s*<([^>]+)>(.*?)</\\1>");
                    Matcher matcher = pattern.matcher(entitlementsContent);
                    enabled = matcher.find();
                } else {
                    // 对于简单的布尔能力，检查是否为true
                    Pattern pattern = Pattern.compile("<key>" + key + "</key>\\s*<true/>");
                    Matcher matcher = pattern.matcher(entitlementsContent);
                    enabled = matcher.find();
                }
                
                capability.setEnabled(enabled);
                capabilities.add(capability);
            }
        }
        
        return capabilities;
    }
}